package com.yupi.springbootinit.utils;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class ExceUtils {

    public static String excelToCsv(MultipartFile multipartFile) throws FileNotFoundException {
//        File file=null;
//
//        try {
//            file = ResourceUtils.getFile("classpath:网站数据.xlsx");
//        } catch (FileNotFoundException e) {
//            throw new RuntimeException(e);
//        }
        List<Map<Integer,String>> list =null;

        try {
            list=EasyExcel.read(multipartFile.getInputStream())
            .excelType(ExcelTypeEnum.XLSX)
            .sheet()
            .headRowNumber(0)
            .doReadSync();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if(CollUtil.isEmpty(list)){
            return "";
        }
        StringBuilder contentData = new StringBuilder();
        LinkedHashMap<Integer,String> header = (LinkedHashMap) list.get(0);
        List<String> headerList = header.values().stream()
                .filter(ObjectUtils::isNotEmpty).collect(Collectors.toList());
        System.out.println(StringUtils.join(headerList,","));
        contentData.append(StringUtils.join(headerList,",")).append("\n");

        for (int i = 1; i < list.size(); i++) {
            LinkedHashMap<Integer,String> data = (LinkedHashMap) list.get(i);
            List<String> dataList = data.values().stream()
                    .filter(ObjectUtils::isNotEmpty).collect(Collectors.toList());
            contentData.append(StringUtils.join(data,",")).append("\n");
            System.out.println(StringUtils.join(dataList,","));
        }
        System.out.println(list);
        return contentData.toString();
    }

    public static void main(String[] args) throws FileNotFoundException {
        excelToCsv(null);
    }
}
